// Created by WXX on 2021/11/10 20:57
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

/**
 * 执行用时：0 ms, 在所有 C++ 提交中击败了100.00%的用户
 * 内存消耗：6 MB, 在所有 C++ 提交中击败了64.80%的用户
 */
class Solution {
public:
    string fractionAddition(string expr) {

        if (expr[0] != '-') expr = '+' + expr;

        int res = 0;
        int a = 1, b = 0;  // b/a
        for (int i = 0; i < expr.size(); ) {
            char op = expr[i++];
            int j = i + 1;
            while (expr[j] >= '0' && expr[j] <= '9' && j < expr.size()) j++;
            int d = stoi(expr.substr(i, j - i));
            i = j + 1;  // 跳过/

            j = i + 1;
            while (expr[j] >= '0' && expr[j] <= '9' && j < expr.size()) j++;
            int c = stoi(expr.substr(i, j - i));

            if (op == '+') {  // b/a + d/c
                add(a, b, c, d);
            } else {  // b/a - d/c
                sub(a, b, c, d);
            }
            i = j;
        }

        if (a < 0) a = -a, b = -b;

        return to_string(b) + "/" + to_string(a);
    }

    void add(int &a, int &b, int c, int d) {
        int x = a * c, y = b * c + a * d;
        int gd = gcd(x, y);
        x /= gd, y /= gd;
        a = x, b = y;
    }

    void sub(int &a, int &b, int c, int d) {
        int x = a * c, y = b * c - a * d;
        int gd = gcd(x, y);
        x /= gd, y /= gd;
        a = x, b = y;
    }

    int gcd(int a, int b) {
        return b ? gcd(b, a % b) : a;
    }
};

int main() {

    cout << Solution().fractionAddition("-1/2+1/2") << endl;  // 0/1
    cout << Solution().fractionAddition("-1/2+1/2+1/3") << endl;  // 1/3
    cout << Solution().fractionAddition("1/3-1/2") << endl;  // -1/6
    cout << Solution().fractionAddition("5/3+1/3") << endl;  // 2/1

    return 0;
}
